package com.example.jf.jfapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.example.jf.jfapp.activity.base.BaseMultipleStatuActivity;
import com.example.jf.jfapp.adapter.CommentAdapter;
import com.example.jf.jfapp.bean.request.CommentRequest;
import com.example.jf.jfapp.bean.response.CommentResponse;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.OkHttpUtils;
import com.example.jf.jfapp.utils.RequestUtils;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.example.jf.jfapp.CommentEditActivity.COMMENT_RESULT_CODE;
import static com.example.jf.jfapp.CommentEditActivity.COMMENT_STATU;

/**
 * Created by jf on 2017/7/29.
 */

public class CommentActivity extends BaseMultipleStatuActivity {
    //动态
    public static final String STATU_ID_KEY = "STATU_ID_KEY";
    protected final static int START_EDIT_COMMENT = 111;

    @BindView(R.id.rl)
    RecyclerView rl;
    CommentResponse mCommentResponse = new CommentResponse();
    CommentAdapter mCommentAdapter;
    private String statuID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        ButterKnife.bind(this);
        initView();
        getData();
    }

    @Override
    public void initView() {
        setToolbar("评论");
        rl = (RecyclerView) findViewById(R.id.rl);
        rl.setLayoutManager(new LinearLayoutManager(this));
        mCommentAdapter = new CommentAdapter(this, mCommentResponse);
        rl.setAdapter(mCommentAdapter);
    }

    @Override
    public void getData() {
        statuID = getIntent().getStringExtra(STATU_ID_KEY);
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        final CommentRequest commentRequest = new CommentRequest(10, statuID);
        Request request = RequestUtils.requestPOST(commentRequest, Constant.URL.GETCOMMENTS);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showErrorView();
                            }
                        });
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();


                ArrayList<CommentResponse.ResultBean> resultBeen = new ArrayList<CommentResponse.ResultBean>();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArr = jsonObject.getJSONArray("result");
                    for (int i = 0; i < jsonArr.length(); i++) {

                        CommentResponse.ResultBean resultBean = new CommentResponse.ResultBean();

                        JSONObject io = jsonArr.getJSONObject(i);

                        resultBean.setContent(io.getString("content"));

                        resultBean.setCreatedAt(io.getString("createdAt"));
                        resultBean.setObjectId(io.getString("objectId"));

                        //单独使用Gson解析
                        String userJson = io.getJSONObject("user").toString();
                        CommentResponse.ResultBean.UserBean userBean = new Gson().fromJson(userJson, CommentResponse.ResultBean.UserBean.class);
                        resultBean.setUser(userBean);
                        Log.e(TAG, "onResponse: " + userBean.toString());

                        //获取回复的Json对象
                        JSONObject replyComment = io.optJSONObject("replyComment");
                        if (replyComment != null) {
                            resultBean.setResultBean(parsingJson(replyComment));
                            Log.e(TAG, "onResponse: " + resultBean.toString());
                        }else{
                            io.getString("objectId");
                        }
                        resultBeen.add(resultBean);
                    }

                    mCommentResponse.addResult(resultBeen);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showContentView();
                            mCommentAdapter.notifyDataSetChanged();
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "onResponse: " + result);
                CommentResponse commentResponse = new Gson().fromJson(result, CommentResponse.class);

                if (commentResponse != null && commentResponse.getResult() != null && commentResponse.getResult().size() > 0) {
                    mCommentResponse.addResult(commentResponse.getResult());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showContentView();
                            mCommentAdapter.notifyDataSetChanged();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showEmptyView();
                        }
                    });
                }
            }
        });
    }

    /**
     * 解析回复数据
     */
    public CommentResponse.ResultBean parsingJson(JSONObject replyComment) throws JSONException {
        CommentResponse.ResultBean commentDataBean = new CommentResponse.ResultBean();
        commentDataBean.setContent(replyComment.getString("content"));
        commentDataBean.setCreatedAt(replyComment.getString("createdAt"));
        commentDataBean.setObjectId(replyComment.getString("objectId"));

        //用户数据
        String userJson = replyComment.getJSONObject("user").toString();
        CommentResponse.ResultBean.UserBean userBean = new Gson().fromJson(userJson, CommentResponse.ResultBean.UserBean.class);
        commentDataBean.setUser(userBean);

        //getJSONObject 这个方法去取json的值，如果没有这个key，那么会直接抛异常
        //optJSONObject 如果没有该key，不会抛异常，会直接返回一个null值
        JSONObject childReplyComment = replyComment.optJSONObject("replyComment");
        if (childReplyComment != null) {
            commentDataBean.setResultBean(parsingJson(childReplyComment));
        }else{
            Log.e(TAG, "parsingJson: " + replyComment.getString("objectId"));
        }
        return commentDataBean;
    }


    @OnClick(R.id.sendComment)
    public void onViewClicked() {
        Intent intent = new Intent(CommentActivity.this, CommentEditActivity.class);
        intent.putExtra(STATU_ID_KEY, statuID);
        startActivityForResult(intent, START_EDIT_COMMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == START_EDIT_COMMENT) {
            switch (resultCode) {
                case COMMENT_RESULT_CODE:
                    boolean statu = data.getBooleanExtra(COMMENT_STATU, false);
                    if (statu) {
                        getData();
                    }
                    break;
            }
        }
    }
}
